<template>
  <div>
    <a-spin :spinning="sending">
      <a-form
        v-show="!isNew"
        id="formLogin"
        ref="formLogin"
        :form="form"
        @submit="handleSubmit"
      >

        <a-form-item class="login-form-item username">
          <a-input
            v-decorator="[
              'username',
              {rules: [{ required: true, message: '请输入帐户名' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
            ]"
            class="login-input"
            @pressEnter="handleSubmit(false)"
          />
        </a-form-item>

        <a-form-item class="login-form-item password">
          <a-input
            v-decorator="[
              'password',
              {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
            ]"
            class="login-input"
            type="password"
            @pressEnter="handleSubmit(false)"
          />
        </a-form-item>

        <a-form-item>
          <a-checkbox
            v-decorator="['remember-me', {
              valuePropName: 'checked',
              initialValue: true
            }]"
          >自动登录</a-checkbox>

          <nuxt-link
            :to="{ name: 'users-ForgotPassword'}"
            class="lost-pwd"
          >忘记密码</nuxt-link>

          <div class="Flex Flex-center" style="text-align: center;">
            <a-button class="primary-btn login-btn" @click="handleSubmit">登录</a-button>
          </div>
        </a-form-item>
      </a-form>
      <a-form
        v-show="isNew"
        id="formNewPwd"
        ref="formNewPwd"
        :form="formNewPwd"
        @submit="handleSubmitNewPwd"
      >
        <a-form-item label="确认密码">
          <div>欢迎您，首次登录户外教育需要先修改密码。</div>
        </a-form-item>
        <a-popover placement="rightTop" trigger="click" :visible="state.passwordLevelChecked">
          <template slot="content">
            <div :style="{ width: '240px' }">
              <div :class="['user-register', passwordLevelClass]">强度：<span>{{ passwordLevelName }}</span></div>
              <a-progress :percent="state.percent" :show-info="false" :stroke-color="passwordLevelColor" />
              <div style="margin-top: 10px;">
                <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
              </div>
            </div>
          </template>
          <a-form-item class="login-form-item password" label="输入密码">
            <a-input
              v-decorator="['password', {rules: [{ required: true, message: '至少6位密码，区分大小写'}, { validator: this.handlePasswordLevel }], validateTrigger: ['change', 'blur']}]"
              class="login-input password"
              size="large"
              type="password"
              autocomplete="false"
              placeholder="至少6位密码，区分大小写"
              @click="handlePasswordInputClick"
            />
          </a-form-item>
        </a-popover>

        <a-form-item class="login-form-item password" label="确认密码">
          <a-input
            v-decorator="['password2', {rules: [{ required: true, message: '至少6位密码，区分大小写' }, { validator: this.handlePasswordCheck }], validateTrigger: ['change', 'blur']}]"
            class="login-input password"
            size="large"
            type="password"
            autocomplete="false"
            placeholder="确认密码"
          />
        </a-form-item>
        <a-form-item>
          <div>
            <a-button class="primary-btn" @click="handleSubmitNewPwd">修改密码</a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script>
// import md5 from 'md5'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import qs from 'qs'

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}

export default {
  name: 'Login',
  layout: 'login-layout',
  auth: false,

  data () {
    return {
      sending: false,
      customActiveKey: 'tab1',
      loginBtn: false,
      isNew: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: process.client ? this.$form.createForm(this) : null,
      formNewPwd: process.client ? this.$form.createForm(this) : null,
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      }
    }
  },

  computed: {
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor () {
      return levelColor[this.state.passwordLevel]
    }
  },

  methods: {
    ...mapActions('user', ['Login', 'Logout']),

    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },

    handleSubmit (e) {
      e && e.preventDefault()

      const {
        form: { validateFieldsAndScroll },
        state,
        customActiveKey,
        extLogin
      } = this
      const that = this

      state.loginBtn = true

      const validateFieldsAndScrollKey = ['username', 'password', 'remember-me']

      validateFieldsAndScroll(validateFieldsAndScrollKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          if (customActiveKey === 'tab2') {
            loginParams.username = values.mobile
            loginParams.password = values.captcha
            loginParams.auth_type = 'sms'
          } else {
            loginParams.username = values.username
            loginParams.password = values.password
          }

          that.sending = true
          this.$auth.loginWith('local', {
            data: qs.stringify(loginParams)
          }).then(
            (resp) => {
              that.sending = false
              extLogin()
              if (this.$auth.$state.user.isNew) {
                this.isNew = true
              } else {
                that.$router.replace('/')
                setTimeout(() => {
                  this.$notification.success({
                    message: '欢迎',
                    description: `${timeFix()}，欢迎回来`
                  })
                }, 1000)
              }
            },
            e => {
              that.sending = false
              this.error = e + ''
              console.log(this.error)
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },

    extLogin () {
      this.$axios.get('api/app/staff/get')
    },

    handlePasswordLevel (rule, value, callback) {
      let level = 0

      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        callback(new Error('密码强度不够'))
      }
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.formNewPwd.getFieldValue('password')
      console.log('value', value)
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },

    handlePasswordInputClick () {
      this.state.passwordLevelChecked = true
    },

    handleSubmitNewPwd () {
      const that = this
      const { formNewPwd: { validateFields }} = this
      validateFields({ force: true }, (err, values) => {
        if (!err) {
          values.username = this.$auth.$state.user.username
          that.sending = true
          this.$authApi.updateNewUserPassword({ ...values })
            .then((res) => {
              that.sending = false
              if (res.data.code === '020002' || res.data.code === '020000') {
                this.$notification.error({
                  message: res.data.mesg,
                  description: `请确认后重新输入`
                })
              } else {
                that.$router.replace('/')
                setTimeout(() => {
                  this.$notification.success({
                    message: '欢迎',
                    description: `${timeFix()}，欢迎回来`
                  })
                }, 1000)
              }
            }).catch(e => {
              that.sending = false
            })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .lost-pwd {
    display: block;
    color:#1890ff;
    cursor: pointer;
    float: right;
  }

  .ant-btn {
    width: 40%;
    border-radius: 20px;
    padding:20px;
    line-height: 0;
    margin-top:30px;
  }

  #formLogin {
    /deep/ .ant-input-affix-wrapper .ant-input-prefix,
    /deep/ .ant-input-affix-wrapper .ant-input-suffix {
      font-size: 16px;
      padding-right: 5px;
      border-right: 1px solid #555;
    }
  }

</style>
